//
//  HomeViewController.m
//  UEHtml-iOSA
//
//  Created by Qun He on 13-9-24.
//  Copyright (c) 2013年 Qun He. All rights reserved.
//

#import "HomeViewController.h"
#import "UEServerInterface.h"
#import "AppDelegate.h"
#import "UIConstanstDefine.h"
#import "UECaseCell.h"
#import "SettingViewController.h"
#import "DetailViewController.h"

#define kTriggerOffSet 100.0f

@interface HomeViewController ()
-(void)receivedData:(UEServerInterface*)sender;
@end

@implementation HomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    ueSI = [[UEServerInterface alloc] initWithDelegate:self responseMethod:@selector(receivedData:)];

    [self loadDataFromServer];
    [self initNavigationBar];
    [self setTitle:@"首页"];
    self.showHomeView = YES;
    
    self.allCaseList = [[UITableView alloc] initWithFrame:UE_NORMAL_VIEW_FRAME];
    self.allCaseList.delegate = self;
    self.allCaseList.dataSource = self;
    self.allCaseList.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.allCaseList.allowsSelectionDuringEditing = NO;
    [self.allCaseList setScrollsToTop:YES];
    [self.view addSubview:self.allCaseList];
    
    if (refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.allCaseList.bounds.size.height, self.view.frame.size.width, self.allCaseList.bounds.size.height)];
		view.delegate = self;
		[self.allCaseList addSubview:view];
		refreshHeaderView = view;
	}
    [refreshHeaderView refreshLastUpdatedDate];
    
    self.caseType = EHomeCase;
}

-(void)initNavigationBar
{
    UIButton *drawerBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 38, 32)];
    [drawerBtn setBackgroundImage:[UIImage imageNamed:@"Drawer_button_normal.png"] forState:UIControlStateNormal];
    [drawerBtn setBackgroundImage:IMAGE_BY_NAMED(@"Drawer_button_select.png") forState:UIControlStateHighlighted];
//    drawerBtn.showsTouchWhenHighlighted = YES;
    [drawerBtn addTarget:self action:@selector(leftBarBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:drawerBtn];
    
    [self.navigationController.navigationBar setBackgroundImage:createImageWithColor(RGBCOLOR(92, 187, 13)) forBarMetrics:UIBarMetricsDefault];//[UIColor greenColor];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-----
#pragma mark -
#pragma mark Other methods

// restore view location
- (void)restoreViewLocation {
    [self.dataAll removeAllObjects];
    [self.allCaseList reloadData];
    homeViewIsOutOfStage = NO;
    CGRect rect = CGRectMake(0.0f,
                             self.navigationController.view.frame.origin.y,
                             self.navigationController.view.frame.size.width,
                             self.navigationController.view.frame.size.height);
    [UIView animateWithDuration:0.2f
                     animations:^{
                         self.navigationController.view.frame = rect;
                     }
                     completion:^(BOOL finished) {
//                         [self renderMainViewAnimation];
                         UIControl *overView = (UIControl *)[[[UIApplication sharedApplication] keyWindow] viewWithTag:10086];
                         [overView removeFromSuperview];
                         
                         if(self.showHomeView)
                         {
                             [self openHomeView];
                         }
                         else
                             [self openSettingView];
                     }];
    
}

-(void)renderMainViewAnimation
{
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.navigationController.view.frame = CGRectMake(0,
                                                                           0,//self.navigationController.view.frame.origin.y,
                                                                           self.navigationController.view.frame.size.width,
                                                                           self.navigationController.view.frame.size.height);
                     }
                     completion:^(BOOL finished){
                         UIControl *overView = (UIControl *)[[[UIApplication sharedApplication] keyWindow] viewWithTag:10086];
                         [overView removeFromSuperview];
                         
                         if(self.showHomeView)
                         {
                             [self openHomeView];
                         }
                         else
                             [self openSettingView];
                     }];
}

// move view to left side
- (void)moveToLeftSide {
    homeViewIsOutOfStage = YES;
    [self animateHomeViewToSide:CGRectMake(-198.0f,
                                           self.navigationController.view.frame.origin.y,
                                           self.navigationController.view.frame.size.width,
                                           self.navigationController.view.frame.size.height)];
}

// move view to right side
- (void)moveToRightSide {
    homeViewIsOutOfStage = YES;
    [self animateHomeViewToSide:CGRectMake(198.0f,
                                           self.navigationController.view.frame.origin.y,
                                           self.navigationController.view.frame.size.width,
                                           self.navigationController.view.frame.size.height)];
}

// animate home view to side rect
- (void)animateHomeViewToSide:(CGRect)newViewRect {
    [UIView animateWithDuration:0.2
                     animations:^{
                         self.navigationController.view.frame = newViewRect;
                     }
                     completion:^(BOOL finished){
                         UIControl *overView = [[UIControl alloc] init];
                         overView.tag = 10086;
                         overView.backgroundColor = [UIColor clearColor];
                         overView.frame = self.navigationController.view.frame;
                         [overView addTarget:self action:@selector(restoreViewLocation) forControlEvents:UIControlEventTouchDown];
                         [[[UIApplication sharedApplication] keyWindow] addSubview:overView];
                     }];
}

// handle left bar btn
- (void)leftBarBtnTapped:(id)sender {
    [SHARE_APPDELEGATE makeLeftViewVisible];
    [self moveToRightSide];
}

//// handle right bar btn
//- (void)rightBarBtnTapped:(id)sender {
//    [(AppDelegate *)[[UIApplication sharedApplication] delegate] makeRightViewVisible];
//    [self moveToLeftSide];
//}

//- (UITableView *)tableViewForTimeScroller:(TimeScroller *)timeScroller {
//    
//    return _tableView;
//    
//}
#if 0
//You should return an NSDate related to the UITableViewCell given. This will be
//the date displayed when the TimeScroller is above that cell.
- (NSDate *)dateForCell:(UITableViewCell *)cell {
    
    NSIndexPath *indexPath = [self.allCaseList indexPathForCell:cell];
    if (indexPath.row == 0) {
        return [NSDate date];
    }
    NSDictionary *dictionary = [self.dataAll objectAtIndex:indexPath.row];
    NSDate *date = [dictionary objectForKey:@"date"];
    
    return date;
    
}
#endif//0

#pragma mark UIScrollViewDelegateMethods
//The TimeScroller needs to know what's happening with the UITableView (UIScrollView)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    [_timeScroller scrollViewDidScroll];
    [refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
//    [_timeScroller scrollViewDidEndDecelerating];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
//    [_timeScroller scrollViewWillBeginDragging];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
//    if (!decelerate) {
//        
//        [_timeScroller scrollViewDidEndDecelerating];
//        
//    }
    [refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    if (scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height) {
        //        if(isReloading)
        //            scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
        NSLog(@"contentOffset X:%0.0f,Y:%0.0f",scrollView.contentOffset.x,scrollView.contentOffset.y);
        NSLog(@"contentWidth: %0.0f, height: %0.0f",scrollView.contentSize.width,scrollView.contentSize.height);
        [self loadMoreData];
    }
}

#pragma mark - ServiceInterface called
-(void)loadDataFromServer
{
    if(isReloading)
    {
        return;
    }
    isReloading = YES;
    isMoreLoading = NO;
    
    [ueSI cancelRequest];
    
    [ueSI ueHtml_getCaseList:@"1" cid:[self getCurrentType] limit:@"15" firstid:@""];
}

-(void)loadMoreData
{
    if(isReloading)
    {
        return;
    }
    isReloading = YES;
    
    isMoreLoading = YES;
    
    NSString* fId = [[self.dataAll lastObject] objectForKey:@"id"];
    if(fId)
    {
        [ueSI cancelRequest];
        [ueSI ueHtml_getCaseList:@"0" cid:[self getCurrentType] limit:@"15" firstid:fId];
    }
}

-(void)receivedData:(UEServerInterface*)sender
{
    NSLog(@"%@", sender.dict);
    isReloading = NO;
    [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.allCaseList];
    if(isMoreLoading)
    {
        [self.dataAll addObjectsFromArray:(NSMutableArray*)sender.dict];
    }
    else
    {
        self.dataAll = [[NSMutableArray alloc] initWithArray:(NSMutableArray*)sender.dict];//[[(NSArray*)sender.dict reverseObjectEnumerator] allObjects]];//(NSMutableArray*)sender.dict;
    }
    isMoreLoading = NO;
    [self.allCaseList reloadData];
}

-(NSString*)getCurrentType
{
    NSInteger realID = (int)self.caseType;
    if(self.caseType == 1)
        realID = 2;
    else if(self.caseType == 2)
        realID = 1;
    return [NSString stringWithFormat:@"%d", realID];
}

#pragma mark UITableViewDelegate Methods


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 122;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.dataAll count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static  NSString *identifier = @"TableViewCell";
    
    UECaseCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        
        cell = [[UECaseCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        
    } 
    
    if([self.dataAll count] >0)
    {
        NSDictionary* dataDict = [self.dataAll objectAtIndex:indexPath.row];
        [cell initWithCaseData:[dataDict objectForKey:@"title"] author:[dataDict objectForKey:@"nickname"] commentCount:[dataDict objectForKey:@"comments"] visitCount:[dataDict objectForKey:@"views"] favorateCount:[dataDict objectForKey:@"likes"]];
        [cell.casePreview setImageFromURL:[NSURL URLWithString:[dataDict objectForKey:@"thumbnail"]]
                         placeHolderImage:nil];
    }
    else
    {
        [cell.casePreview setImageFromURL:nil placeHolderImage:nil];
    }
    
//    NSDictionary *dictionary = [self.dataAll objectAtIndex:indexPath.row];
//    NSString *title = [dictionary objectForKey:@"title"];
//    cell.textLabel.text = title;
//    
//    NSDate *date = [dictionary objectForKey:@"date"];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
//    cell.detailTextLabel.text = [dateFormatter stringFromDate:date];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DetailViewController* detail = [[DetailViewController alloc] init];
    detail.caseTitle = [[self.dataAll objectAtIndex:indexPath.row] objectForKey:@"title"];
    detail.caseID = [[self.dataAll objectAtIndex:indexPath.row] objectForKey:@"id"];
    detail.view.frame = self.view.frame;
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark - EGORefreshTableHeaderDelegate Method
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
    return isReloading;
}

-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
    return [NSDate date];
}

-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
    [self loadDataFromServer];
}

-(void)openSettingView
{
//    homeView = self.view;
    SettingViewController* sVC = [[SettingViewController alloc] init];
    sVC.view.frame = self.view.bounds;
    self.navigationController.viewControllers = [NSArray arrayWithObject:sVC];
//    [self.navigationController pushViewController:sVC animated:YES];
//    self.view = sVC.view;
}

-(void)openHomeView
{
    self.navigationController.viewControllers = [NSArray arrayWithObject:self];
//    self.view = homeView;
    if(self.needReloadData)
    {
        [self loadDataFromServer];
    }
}

@end
